<?php

namespace app\api\controller\wanlshop;

use app\common\controller\Api;
use fast\Tree;
use think\Db;

/**
 * WanlShop店铺接口
 */
class Shop extends Api
{
    protected $noNeedLogin = ['getShopInfo', 'community', 'getShopList'];
    protected $noNeedRight = ['*'];
	
	public function _initialize()
	{
	    parent::_initialize();
		$this->model = model('app\api\model\wanlshop\Shop');
	}

    /*
     *社区店
     */
    public function community(){
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $longitude = $this->request->post('longitude');
            $latitude = $this->request->post('latitude');
            $where['status'] = '';
            $data = model('app\common\model\SpeechShop')
                ->where($where)
                ->field('id,name,address,mobile,longitude,latitude')
                ->order('id desc')
                ->paginate($this->request->post('rows'));
            foreach($data as $key=>$value){
                $data[$key]['img'] = 'https://t-zhjk.yuanzai1999.com/assets/img/1shequshengtu.png';
                $data[$key]['distance'] = self::getDistance($longitude?:0,$latitude?:0,$longitude?$value['longitude']:0,$latitude?$value['latitude']:0,1,0);
                unset($data[$key]['longitude']);
                unset($data[$key]['latitude']);
            }

            $this->success('返回成功', $data);
        }
        $this->error(__('非法请求'));
    }

    /*
     *计算距离
     */
    private function getDistance($longitude1, $latitude1, $longitude2, $latitude2, $unit=2, $decimal=2){
        $EARTH_RADIUS = 6370.996; // 地球半径系数
        $PI = 3.1415926;

        $radLat1 = $latitude1 * $PI / 180.0;
        $radLat2 = $latitude2 * $PI / 180.0;

        $radLng1 = $longitude1 * $PI / 180.0;
        $radLng2 = $longitude2 * $PI /180.0;

        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;

        $distance = 2 * asin(sqrt(pow(sin($a/2),2) + cos($radLat1) * cos($radLat2) * pow(sin($b/2),2)));
        $distance = $distance * $EARTH_RADIUS * 1000;

        if($unit==2){
            $distance = $distance / 1000;
        }

        return round($distance, $decimal);
    }

	/**
	 * 视频宝贝链接
	 */
	public function videogood()
	{
		if ($this->request->isPost()) {
			$data = model('app\api\model\wanlshop\Goods')
            ->where('shenhe',1)
            ->where('status', 'normal')
			->field('id,title,price')
            ->order('id', 'desc')
            ->select();
			$this->success('返回成功', $data);
		}
		$this->error(__('非法请求'));
	}
    
    /**
	 * 商家视频素材
	 *
	 * @ApiSummary  ()
	 * @ApiMethod   (POST)
	 */
	public function videos()
	{
		if ($this->request->isPost()) {
			$params = $this->request->post();
			$data = [
				'name' => $params['title'],
				'user_id' => $this->auth->id,
				'image' => $params['video'],
				'trademark' => $params['logw'],
				'number' => $params['latw'],
				'state' => 1
			];
			model('app\api\model\wanlshop\Auth')->data($data)->save();
			$this->success('返回成功', $params);
		}
		$this->error(__('非法请求'));
	}

	/**
	 * 商家视频主页
	 *
	 * @ApiSummary  ()
	 * @ApiMethod   (POST)
	 */
	public function videosList()
	{
		if ($this->request->isPost()) {
			$data = model('app\api\model\wanlshop\Auth')
                ->where(['state' => 1])
                ->field('id,name,image AS video')
				->order('id desc')
				->select();;
			$this->success('返回成功', $data);
		}
		$this->error(__('非法请求'));
	}

	/**
	 * 首页视频发现
	 */
	public function homevideo()
	{
		if ($this->request->isPost()) {
			$data = model('app\api\model\wanlshop\Auth')
                ->where(['state' => 9])
                ->field('id,name,image AS video')
				->order('id desc')
				->select();
			foreach ($data as $key => $value) {
				$data[$key]['coverimg'] = model('app\api\model\wanlshop\Goods')->where('shenhe',1)->where('status', 'normal')->value("image");
				$data[$key]['goods'] = model('app\api\model\wanlshop\Goods')->where('shenhe',1)->where('status', 'normal')->field('id,title,price')->find();
			}
			$this->success('返回成功', $data);
		}
		$this->error(__('非法请求'));
	}
    
    
    /**
	 *
	 * @ApiSummary  店铺
	 * @ApiMethod   (GET)
	 *
	 * @param 
	 */
	public function getShopList()
	{
		//设置过滤方法
		$this->request->filter(['strip_tags']);
        
		$where['deletetime']=null;
		$shop_type=$this->request->post('shop_type');
        if($shop_type){
           $where['shop_type']=$shop_type;
		}

		// 获取店铺信息
		$data = \think\Db::name("wanlshop_shop")
				->field('id,shopname,avatar,city')
				->where($where)
                ->order('id asc')
				->select();
		$this->success('返回成功', $data);
	}
	
	/**
	 *
	 * @ApiSummary  店类
	 * @ApiMethod   (GET)
	 *
	 * @param 
	 */
	public function getBranList()
	{
		//设置过滤方法
		$this->request->filter(['strip_tags']);
		// 获取店铺信息
		$data = model('app\api\model\wanlshop\Brand')
				->field('id,name,image')
                ->order('id asc')
				->select();
		$this->success('返回成功', $data);
	}
	
	/**
	 * 一次性获取店铺相关数据 1.0.8升级
	 *
	 * @ApiSummary  (WanlShop 一次性获取店铺相关数据)
	 * @ApiMethod   (GET)
	 *
	 * @param string $id 页面ID
	 */
	public function getShopInfo($id = null)
	{
		//设置过滤方法
		$this->request->filter(['strip_tags']);
		// 获取店铺信息
		$row = $this->model->get($id);
		if (!$row) {
		    $this->error(__('未找到此商家'));
		}
		// 获取商家类目
		$tree = Tree::instance();
		$tree->init(
			model('app\api\model\wanlshop\ShopSort')
				->where(['shop_id' => $row['id']])
				->field('id, pid, name, image')
				->order('weigh asc')
				->select()
		);
		$row['category'] = $tree->getTreeArray(0);
		// 查看是否被关注
		$row['isFollow'] = model('app\api\model\wanlshop\find\Follow')
			->where([
				'user_no' => $row['find_user']['user_no'], 
				'user_id' => $this->auth->id
			])
			->count();
		$row['isLive'] = model('app\api\model\wanlshop\Live')
			->where(['shop_id' => $row['id'], 'state' => 1])
			->field('id')
			->find();
		// 获取类目样式配置
		$shopConfig = model('app\api\model\wanlshop\ShopConfig')
			->where(['shop_id' => $row['id']])
			->find();
		$row['categoryStyle'] = (int)$shopConfig['category_style'];
		// 获取商家自定义页面
		$row['page'] = model('app\api\model\wanlshop\Page')
			->where([
				'shop_id' => $row['id'], 
				'type' => 'shop'
			])
			->field('id, name, page, item')
			->find();
		$this->success('返回成功', $row);
	}

	/**
	 * @ApiSummary  (WanlShop 一次性获取店铺后台管理相关数据)
	 * @ApiMethod   (GET)
	 *
	 * @param string $id 页面ID
	 */
	public function getShopAdminInfo()
	{
		$shop_info=model('app\api\model\wanlshop\Shop')
					->field('id,shopname,pay_code_img')
					->where('user_id',$this->auth->id)
					// ->where('user_id',1)
					->where('deletetime',null)
					->find();
	    if(!$shop_info){
		  $this->error(__('您当前未开通店铺'));
		}

		$start_time=$this->request->post('start_time',date('Y-m-d'));
		$end_time=$this->request->post('end_time',date('Y-m-t'));

		$whereOrder['createtime']=['between',[strtotime($start_time.' 00:00:00'),strtotime($end_time.' 23:59:59')]];
		$whereOrder['shop_id']=$shop_info['id'];
		// 待付款
		$data['order_count']['wait_pay']=model('app\api\model\wanlshop\Order')
					->where('state',1)
					->where($whereOrder)
					->count();
		// 待发货
		$data['order_count']['wait_sending']=model('app\api\model\wanlshop\Order')
					->where('state',2)
					->where($whereOrder)
					->count();
		// 待收货
		$data['order_count']['wait_receive']=model('app\api\model\wanlshop\Order')
					->where('state',3)
					->where($whereOrder)
					->count();
		// 已完成
		$data['order_count']['complete']=model('app\api\model\wanlshop\Order')
					->where('state',6)
					->where($whereOrder)
					->count();

		// 成交金额
		$whereDataMoney['createtime']=['between',[strtotime($start_time.' 00:00:00'),strtotime($end_time.' 23:59:59')]];
		$whereDataMoney['shop_id']=$shop_info['id'];
		$data['data_count']['deal_money']=model('app\api\model\wanlshop\Pay')
		            ->where('pay_state',1)
					->where($whereDataMoney)
					->sum('price');
		// 成交订单数
	    $whereDatNum['paymenttime']=['between',[strtotime($start_time.' 00:00:00'),strtotime($end_time.' 23:59:59')]];
		$whereDatNum['shop_id']=$shop_info['id'];
		$data['data_count']['deal_num']=model('app\api\model\wanlshop\Order')
					->where($whereDatNum)
					->count();

		$data['pay_code_img']=$shop_info['pay_code_img'];
		$data['shop_name']=$shop_info['shopname'];
		$this->success('返回成功', $data);
	}
	
	/**
	 * 商家入驻-详情
	 */
	public function applyDetails()
	{
		$this->request->filter(['strip_tags']);
		if ($this->request->isPost()) {
			$data = model('app\common\model\Auth')
			->where(['user_id' => $this->auth->id])
			->find();

			$data['open_pay_status']=0;
			$data['open_pay_remark']='';
			if($data['verify']==3){
				$open_pay=Db::name('shangfutong_applyment_notify')
						->field('state,remark')
						->where('subApplyId',$data['applicationId'])
						->order('id desc')
						->find();

				if($open_pay){
					$data['open_pay_status']=$open_pay['state']==2?1:0;
					$data['open_pay_remark']=$open_pay['remark']??'';
				}
			}
			$this->success('返回成功', $data);
		}
		$this->error(__('非法请求'));
	}
	
	/**
	 * 商家入驻-申请
	 */
	public function apply()
	{
		//设置过滤方法
		$this->request->filter(['strip_tags']);

		$data=$this->request->Post();

        if(!isset($data['verify'])){
		    $this->error(__('当前上传类型verify必传'));
		}

		$find=model('app\common\model\Auth')->where('user_id',$this->auth->id)->value('id');
  
		if($find){
			if(isset($data['deletetime'])){unset($data['deletetime']);}
			$res=model('app\common\model\Auth')->where('user_id',$this->auth->id)->update($data);
		}else{
		    $data['user_id']=$this->auth->id;
			$res=model('app\common\model\Auth')->save($data);
		}

		if($res){
			$this->success('请求成功');
		}else{
		    $this->error(__('请求失败'));
	    }
	}
}